<!DOCTYPE html>
<html>
<head>
    <title>WebSocket测试</title>
    <meta charset="UTF-8">
</head>
<body>
    <h1>WebSocket连接测试</h1>
    <div id="status" style="padding: 10px; border: 1px solid #ccc; margin: 10px 0;">
        状态: 准备连接...
    </div>
    <div id="messages" style="height: 300px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
        <div>等待连接...</div>
    </div>
    <button onclick="connect()">连接WebSocket</button>
    <button onclick="disconnect()">断开连接</button>
    <button onclick="sendTestMessage()">发送测试消息</button>
    
    <script>
        let ws = null;
        const status = document.getElementById('status');
        const messages = document.getElementById('messages');
        
        function addMessage(message) {
            const div = document.createElement('div');
            div.innerHTML = new Date().toLocaleTimeString() + ': ' + message;
            messages.appendChild(div);
            messages.scrollTop = messages.scrollHeight;
        }
        
        function connect() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                addMessage('WebSocket已经连接');
                return;
            }
            
            // 连接到WebSocket端点
            ws = new WebSocket('ws://localhost:8080/ws/task-notification/2');
            
            ws.onopen = function(event) {
                status.innerHTML = '状态: <span style="color: green;">已连接</span>';
                addMessage('WebSocket连接已建立');
            };
            
            ws.onmessage = function(event) {
                addMessage('收到消息: ' + event.data);
            };
            
            ws.onclose = function(event) {
                status.innerHTML = '状态: <span style="color: red;">连接已关闭</span>';
                addMessage('WebSocket连接已关闭: ' + event.code + ' - ' + event.reason);
            };
            
            ws.onerror = function(error) {
                status.innerHTML = '状态: <span style="color: red;">连接错误</span>';
                addMessage('WebSocket错误: ' + error);
            };
        }
        
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }
        
        function sendTestMessage() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                const message = JSON.stringify({
                    type: 'test',
                    message: 'Hello WebSocket!',
                    timestamp: new Date().getTime()
                });
                ws.send(message);
                addMessage('发送消息: ' + message);
            } else {
                addMessage('WebSocket未连接，无法发送消息');
            }
        }
    </script>
</body>
</html>
